<template>
  <div>
    <el-form @submit.native.prevent class="query-table-form" :inline="true">
      <el-form-item>
        <el-date-picker
          v-model="queryDate"
          :clearable="false"
          :disabled="+searchType === 1"
          class="w-100"
          type="month"
          @change="getCountData()"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <c-select
          :options="{
            0: '时间查询',
            1: '全部数据',
          }"
          v-model="searchType"
          @change="getCountData()"
          :loading="selectLoading"
        ></c-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="getCountData()">查询</el-button>
      </el-form-item>
    </el-form>
    <div class="mb-3" v-loading="countLoading">
      <table class="table table-bordered text-center">
        <tbody>
          <tr class="font-weight-bold bg-light">
            <td colspan="2">担保费合同金额</td>
            <td colspan="2">累计应收担保费</td>
            <td colspan="2">累计实收担保费</td>
            <td colspan="2">当期预收担保费</td>
            <td colspan="2">当期欠收担保费</td>
          </tr>
          <tr>
            <td>笔数</td>
            <td>金额(万元)</td>
            <td>笔数</td>
            <td>金额(万元)</td>
            <td>笔数</td>
            <td>金额(万元)</td>
            <td>笔数</td>
            <td>金额(万元)</td>
            <td>笔数</td>
            <td>金额(万元)</td>
          </tr>
          <tr>
            <td>{{ countData.warrant_contract_total || '-' }}</td>
            <td>{{ countData.warrant_contract_funds || '-' }}</td>
            <td>{{ countData.warrant_due_total || '-' }}</td>
            <td>{{ countData.warrant_due_funds || '-' }}</td>
            <td>{{ countData.warrant_actual_total || '-' }}</td>
            <td>{{ countData.warrant_actual_funds || '-' }}</td>
            <td>{{ countData.warrant_pre_total || '-' }}</td>
            <td>{{ countData.warrant_pre_funds || '-' }}</td>
            <td>{{ countData.warrant_owe_total || '-' }}</td>
            <td>{{ countData.warrant_owe_funds || '-' }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <el-form class="query-table-form" @submit.native.prevent :inline="true" :model="params">
      <el-form-item>
        <el-input
          v-model="params.customer_name"
          placeholder="项目名称查询"
          clearable
          @change="getTableData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-input
          v-model="params.corp_name"
          placeholder="负责人查询"
          clearable
          @change="getTableData()"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <select-address
          v-model="params.address_code"
          placeholder="地址查询"
          auto-top
          clearable
          @change="getTableData()"
        ></select-address>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" @click="getData()">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-download"
          :loading="exportLoading"
          @click="exportExcel('保费统计列表')"
        >
          导出列表
        </el-button>
      </el-form-item>
      <div class="text-muted" v-loading="countLoading2">
        项目数量：
        <span class="text-primary">{{ customerCount || '-' }}</span>
        。保费登记条数：
        <span class="text-primary">{{ totalCount || '-' }}</span>
      </div>
    </el-form>

    <c-table
      border
      v-loading="loading"
      :stripe="false"
      :columns="tableColumns"
      :data="tableData"
      @sort-change="handleSortChange"
    >
      <template v-slot:projectName="scope">
        <div class="project-history text-primary cursor-pointer" @click="handleDetail(scope.row)">
          {{ scope.row.customer_name }}
        </div>
      </template>
    </c-table>

    <div class="query-pagination">
      <div></div>
      <el-pagination
        layout="total, prev, pager, next, jumper"
        :current-page.sync="params.index"
        :page-size="params.size"
        :total="totalCount"
        @current-change="getTableData"
      ></el-pagination>
    </div>

    <project-detail-dialog
      :visible.sync="detailVisible"
      :related-id="detailId"
      :project-data="projectData"
    ></project-detail-dialog>
  </div>
</template>

<script>
import SelectAddress from '@/components/select/SelectAddress'
import { mapGetters } from 'vuex'
import { exportExcel } from '@/credit/mixin/taskTableProvinceUnion'
import ProjectDetailDialog from '@/bigcredit/views/settle/stat/components/ProjectDetailDialog'

export default {
  components: {
    SelectAddress,
    ProjectDetailDialog,
  },
  data() {
    return {
      countLoading: false,
      countLoading2: false,
      loading: false,
      params: {
        index: 1,
        size: 10,
        customer_name: '',
        corp_name: '',
        address_code: '',
        'gua_type.eq': '',
        'service_id.eq': '',
      },
      order: {
        due_warrant_date: 'desc',
      },

      tableColumns: [
        { attrs: { label: '序号', prop: 'index', align: 'center', width: 100 } },
        { attrs: { label: '单号', prop: 'order_no', width: 120, sortable: 'order_no' } },
        {
          attrs: {
            label: '贷款主体名称',
            prop: 'customer_name',
            width: 130,
            sortable: 'customer_name',
          },
          slot: 'projectName',
        },
        { attrs: { label: '证件号码', prop: 'idNo', width: 120 } },
        {
          attrs: {
            label: '法人名称',
            prop: 'corp_name',
            align: 'center',
            width: 100,
            sortable: 'corp_name',
          },
        },
        {
          attrs: {
            label: '借款人联系电话',
            prop: 'mobile_no',
            align: 'center',
            width: 140,
            sortable: 'mobile_no',
          },
        },
        { attrs: { label: '贷款银行', prop: 'bank_name', width: 120, sortable: 'bank_name' } },
        {
          attrs: {
            label: '担保金额(万元)',
            prop: 'reply_funds',
            align: 'center',
            width: 140,
            sortable: 'reply_funds',
          },
        },
        { attrs: { label: '担保开始时间', prop: 'loadDate', width: 130, sortable: 'load_date' } },
        {
          attrs: {
            label: '担保结束时间',
            prop: 'loadEndDate',
            width: 130,
            sortable: 'load_end_date',
          },
        },
        {
          attrs: {
            label: '贷款期限',
            prop: 'months',
            align: 'center',
            width: 100,
            sortable: 'months',
          },
        },
        {
          attrs: {
            label: '担保费利率',
            prop: 'gua_rate',
            align: 'center',
            width: 120,
            sortable: 'gua_rate',
          },
        },
        {
          attrs: {
            label: '担保费合同金额(万元)',
            prop: 'gua_fee',
            align: 'center',
            width: 120,
            sortable: 'gua_fee',
          },
        },
        {
          attrs: {
            label: '当期应收保费时间',
            prop: 'dueWarrantDate',
            align: 'center',
            width: 100,
            sortable: 'due_warrant_date',
          },
        },
        {
          attrs: {
            label: '当期应收缴担保费',
            prop: 'due_warrant_fee',
            align: 'center',
            width: 100,
            sortable: 'due_warrant_fee',
          },
        },
        {
          attrs: {
            label: '当期实收担保费金额',
            prop: 'actual_warrant_fee',
            align: 'center',
            width: 100,
            sortable: 'actual_warrant_fee',
          },
        },
        {
          attrs: {
            label: '收到上期欠款金额',
            prop: 'owe_warrant_fee_coll',
            width: 100,
            sortable: 'owe_warrant_fee_coll',
          },
        },
        {
          attrs: {
            label: '当期预收担保金额',
            prop: 'pre_warrant_fee',
            width: 100,
            sortable: 'pre_warrant_fee',
          },
        },
        {
          attrs: {
            label: '当期欠收担保费金额',
            prop: 'owe_warrant_fee',
            width: 100,
            sortable: 'owe_warrant_fee',
          },
        },
      ],
      tableData: [],
      totalCount: 0,

      datePicked: [],
      countData: {},
      queryDate: '',
      tableName: 'credit_warrant_fee_statistics_list',
      exportLoading: false,
      customerCount: '',

      detailId: '',
      detailVisible: false,
      projectData: {},

      lastDate: '',
      searchType: '0',
      selectLoading: false,
    }
  },
  computed: {
    ...mapGetters(['clientId']),
  },
  watch: {},
  created() {
    this.queryDate = this.$utils.dateFormat(new Date(), 'yyyy-MM')
    this.params['service_id.eq'] = this.clientId
    this.getData()
    this.getLastDate()
  },
  mounted() {},
  methods: {
    getLastDate() {
      this.selectLoading = true
      this.$api
        .getData('credit', 'common/statistics/', {
          'apiKey.kv': 'last-due-date',
          'service_id.kv': this.clientId,
        })
        .then(res => {
          const data = res.data ?? {}
          this.lastDate = this.$utils.dateFormat(data.due_warrant_date, 'yyyy-MM')
        })
        .finally(() => {
          this.selectLoading = false
        })
    },
    handleDetail(row = {}) {
      this.projectData = { ...row }
      this.detailId = row.customer_related_id
      this.detailVisible = true
    },
    handleSortChange({ order, column }) {
      if (!order) {
        this.order = { due_warrant_date: 'desc' }
      } else {
        this.order = {}
        this.order[column.sortable] = order.includes('asc') ? 'asc' : 'desc'
      }
      this.getData()
    },
    dataAdapter(item, index) {
      item.index = this.totalCount - index - this.params.size * (this.params.index - 1)
      item.idNo = +item.customer_type === 1 ? item.register_no : item.lender_idcard
      item.loadDate = this.$utils.dateFormat(item.load_date, 'yyyy-MM-dd')
      item.loadEndDate = this.$utils.dateFormat(item.load_end_date, 'yyyy-MM-dd')
      item.dueWarrantDate = this.$utils.dateFormat(item.due_warrant_date, 'yyyy-MM-dd')
      return item
    },
    fetchData(params) {
      return this.$utils.promise(
        this.$api.getData(this.$serviceName, this.tableName, params, this.order || {})
      )
    },
    async exportExcel(filename) {
      this.exportLoading = true
      exportExcel({
        filename,
        tableColumns: this.tableColumns,
        params: this.params,
        dataAdapter: this.dataAdapter,
        fetchData: this.fetchData,
        onLoaded: () => {
          this.exportLoading = false
        },
      })
    },
    getCountCustomer() {
      this.countLoading2 = true
      this.$api
        .getData(this.$serviceName, this.tableName, {
          ...this.params,
          index: 1,
          size: 1,
          groupFields: 'customer_related_id',
        })
        .then(res => {
          this.customerCount = res?.data?.totalCount ?? 0
        })
        .finally(() => {
          this.countLoading2 = false
        })
    },
    getCountData() {
      let date = ''
      if (+this.searchType === 1) {
        this.queryDate = this.lastDate
        date = this.lastDate
      } else {
        date = this.queryDate
      }
      this.countLoading = true
      this.$http
        .get(
          `/api/credit/warrant/statistics/?apiKey=warrant-fee&month=${this.$utils.dateFormat(
            date,
            'yyyy-MM'
          )}&service_id=${this.clientId}`
        )
        .then(res => {
          this.countData = res?.data || {}
        })
        .finally(() => {
          this.countLoading = false
        })
    },
    getTableData(index = 1) {
      this.params.index = index
      // this.params['due_warrant_date.gt'] = this.$utils.dateFormat(this.queryDate, 'yyyy-MM')
      // const date = new Date(this.queryDate)
      // this.params['due_warrant_date.lt'] = this.$utils.dateFormat(
      //   `${date.getFullYear()}-${new Date(this.queryDate).getMonth() + 2}`,
      //   'yyyy-MM'
      // )
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          this.totalCount = res?.data?.totalCount ?? 0
          this.tableData = (res?.data?.data ?? []).map(this.dataAdapter)
        })
        .finally(() => {
          this.loading = false
        })
    },
    getData() {
      this.getCountData()
      this.getTableData()
      this.getCountCustomer()
    },
  },
}
</script>
<style lang="scss" scoped></style>
